package cn.hn3l.dao.implement;

import cn.hn3l.dao.interfaces.DaoBookcase;
import cn.hn3l.dao.interfaces.DaoBookinfo;
import cn.hn3l.dao.interfaces.DaoBooktype;
import cn.hn3l.model.Bookcase;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by weiwei02 on 2016/8/29.
 */
public class DaoBookcaseImpl implements DaoBookcase {
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Override
    public Bookcase getBookcase(Long bookcase) {
        String sql = "select * from tb_bookcase where id = ?";
        RowMapper<Bookcase> rowMapper = BeanPropertyRowMapper.newInstance(Bookcase.class);
        List<Bookcase> list = jdbcTemplate.query(sql, rowMapper, bookcase);
        return list.get(0);
    }

    @Override
    public List<Bookcase> getAllBookcase() {
        String sql = "select * from tb_bookcase";
        RowMapper<Bookcase> rowMapper = BeanPropertyRowMapper.newInstance(Bookcase.class);
        List<Bookcase> list = jdbcTemplate.query(sql, rowMapper);
        return list;
    }

    @Override
    public boolean addNewBookcase(String value) {
        String sql = "insert into bookmanger.tb_bookcase(name) values (?)";
        if (jdbcTemplate.update(sql,value) > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean deleteBookcase(String value) {
        String sql = "DELETE FROM bookmanger.tb_bookcase WHERE bookmanger.tb_bookcase.name = ?";
        if (bookcaseCanDeleted(value)){
            if (jdbcTemplate.update(sql,value) > 0){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean alterNameFromBookcase(String value1, String value2) {
        String sql = "UPDATE bookmanger.tb_bookcase SET bookmanger.tb_bookcase.name = ?" +
                " WHERE bookmanger.tb_bookcase.name = ? ";
        if (jdbcTemplate.update(sql, value2, value1) > 0){
            return true;
        }
        return false;
    }

    @Override
    public int findIdByName(String value) {
        String sql = "SELECT id FROM bookmanger.tb_bookcase WHERE bookmanger.tb_bookcase.name = ?";
        return jdbcTemplate.queryForObject(sql, Integer.class, value);
    }

    @Resource
    private DaoBookinfo daoBookinfo;

    private boolean bookcaseCanDeleted(String value) {
        String sql = "SELECT id FROM bookmanger.tb_bookcase WHERE bookmanger.tb_bookcase.name = ?";
        if (daoBookinfo.getBookCountFromBookcaseId(jdbcTemplate.queryForObject(sql, Integer.class, value)) > 0){
            return false;
        }
        return true;
    }
}
